
import json
from math import e
from uikit_codes import GenerateUIKitCodes
import os
import subprocess
import string
import random
from generate_words_util import GenerateWordsUtil

class GnnerateSwiftCode:

    def __init__(self, json_path=None):

        self.gen_words = GenerateWordsUtil()

        if not json_path:
            json_path = "output_jsons/test.json"
            
        self.generate_swift_code_from_json(json_path)
    
    def generate_swift_code_from_json(self, json_path):
        # 读取JSON文件
        with open(json_path, 'r') as file:
            data = json.load(file)
        
        gene_uikit = GenerateUIKitCodes()

        # 生成Swift代码
        code = ""
        snapkit = ""

        # 前缀
        prefix = data.get('prefix', '')
        if prefix:
            # 随机两到三个大写字母
            prefix = ''.join(random.choices(string.ascii_uppercase, k=random.randint(2, 3)))

        moudle_name = data.get('moudle', '')
        if not moudle_name:
            moudle_name = "Test"

        father_class = ''
        class_name = ''
        class_type = data.get('classType', '')
        if class_type == 'CATBaseTipView':
            father_class = class_type
            class_name = prefix + moudle_name + "PopView"
        else:
            if class_type in ['UIViewController', 'UITableView', 'UICollectionView']:
                father_class = 'UIViewController'
                class_name = prefix + moudle_name + "Controller"
            else:
                father_class = 'UIView'
                class_name = prefix + moudle_name + "View"
        
            
        if "subviews" in data:
            for i, subview in enumerate(data["subviews"]):
                sub_prefix = f"sub{i}_"
                # 修复：正确处理元组返回值
                view_code, constraint_code = gene_uikit.create_view(subview, var_prefix=sub_prefix, father_view="self.vhbsView")
                code += view_code
                snapkit += constraint_code
        
        method_name = random.choice(['config', 'setup', 'init', 'start']) + GenerateWordsUtil.upper_first_letter(self.gen_words.generate_words(2)) + random.choice(['UI', 'Views', 'SubViews'])


        # 生成更规范的Swift代码
        codes = []
        codes.append("import UIKit\n\nimport SnapKit\n\n")
        codes.append("@objcMembers\n")
        codes.append(f"public class {class_name}: {father_class} {{\n\n")

        codes.append(code)

        codes.append("    override init(frame: CGRect) {\n")
        codes.append("        super.init(frame: frame)\n")
        codes.append(f"        {method_name}()\n")
        codes.append("    }\n\n")
        codes.append("    required init?(coder: NSCoder) {\n")
        codes.append("        super.init(coder: coder)\n")
        codes.append(f"        {method_name}()\n")
        codes.append("    }\n\n")
        codes.append(f"    private func {method_name}() {{\n")
        codes.append("        // UI组件初始化\n")

        codes.append(snapkit)

        codes.append("    }\n")

        if gene_uikit.actions:
            codes.append("\n\n".join(gene_uikit.actions))
        
        if class_type == 'CATBaseTipView':
            codes.append(gene_uikit.generate_class_method(class_name, is_class_return=data.get('is_class_return', True)))


        codes.append("}\n")

        file_path = "swift_codes"
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        
        code = "".join(codes)

        swift_file_path = os.path.join(file_path, f"{class_name}.swift")
        with open(swift_file_path, "w") as file:
            file.write(code)
        
        # 添加Swift代码格式化
        self.format_swift_code(swift_file_path)
    
    # 在format_swift_code方法中添加验证
    def format_swift_code(self, swift_file_path):
        """格式化Swift代码"""
        # 先验证文件
        if not self.validate_swift_file(swift_file_path):
            print(f"文件验证失败，跳过格式化: {swift_file_path}")
            return
            
        try:
            print("格式化Swift代码...")
            # 使用swiftformat工具格式化代码
            result = subprocess.run(
                [
                    "swiftformat", 
                    swift_file_path, 
                    "--indent", "4",
                    "--allman", "false",  # 大括号不换行
                    "--swiftversion", "5.0",
                    "--disable", "redundantObjc",  # 禁止移除 @objc
                    "--verbose"  # 添加详细输出
                ], 
                check=False,  # 不要在失败时抛出异常
                capture_output=True,  # 捕获输出
                text=True  # 以文本形式返回输出
            )
            
            if result.returncode == 0:
                print(f"Swift代码格式化成功: {swift_file_path}")
            else:
                print(f"Swift代码格式化失败: {result.stderr}")
                print("请确保已安装swiftformat工具，可通过'brew install swiftformat'安装")
        except Exception as e:
            print(f"Swift代码格式化错误: {e}")
            print("请确保已安装swiftformat工具，可通过'brew install swiftformat'安装")
    
    def validate_swift_file(self, swift_file_path):
        """验证Swift文件的基本语法结构"""
        with open(swift_file_path, 'r') as file:
            content = file.read()
        
        # 检查括号是否匹配
        open_braces = content.count('{')
        close_braces = content.count('}')
        
        if open_braces != close_braces:
            print(f"警告：文件中的大括号不匹配！打开的大括号：{open_braces}，闭合的大括号：{close_braces}")
            return False
        
        return True
if __name__ == "__main__":
    # GnnerateSwiftCode("output_jsons/访客非会员提示.json")

    # 遍历output_jsons目录下的所有JSON文件
    for filename in os.listdir("output_jsons"):
        if filename.endswith(".json"):
            json_path = os.path.join("output_jsons", filename)
            GnnerateSwiftCode(json_path)